<script>
	import auth from '@/utils/auth'
	import config from '@/config'
	import request from '@/utils/request'

	export default {
		onLaunch() {
			console.log('App Launch')
            console.log('当前页面：' + window.location.href)

            // #ifdef H5
			this.initH5Auth()
			// #endif
		},
		onShow() {
			console.log('App Show')
		},
		onHide() {
			console.log('App Hide')
		},
		watch: {

		},
		methods: {
			// 初始化H5认证
			async initH5Auth() {
				// 检查是否在微信浏览器中
				const isWxBrowser = navigator.userAgent.toLowerCase().includes('micromessenger')
				if (!isWxBrowser) {
					uni.showModal({
						title: '提示',
						content: '请在微信中打开',
						showCancel: false
					})
					return
				}
				
				// 获取alias参数
				const alias = this.getUrlParam('alias')
				if (!alias) {
					uni.showModal({
						title: '提示',
						content: '无效的访问链接，请重新打开',
						showCancel: false
					})
					return
				}

                // 如果alias不存在或者是alias不相同则更新alias
				if (!uni.getStorageSync('alias') || uni.getStorageSync('alias') !== alias) {
					// 清空token
					uni.removeStorageSync(alias + '_token')
					// 保存alias
					uni.setStorageSync('alias', alias)
					// 获取公众号配置
					const res = await this.getWxConfig()
					if (res.code === 0 && res.data.wechat_app_id) {
						console.log('获取到公众号appid' + alias + ' => ' + res.data.wechat_app_id)
						// 保存appid
						uni.setStorageSync(alias + '_wx_appid', res.data.wechat_app_id)
						// 检查登录状态
						await this.checkWxH5Auth()
					} else {
						uni.showModal({
							title: '提示',
							content: '获取配置失败，请刷新重试',
							showCancel: false
						})
					}
				}
			},
			
			// 获取公众号配置
			getWxConfig() {
				return request({
					url: '/wechat/config',
					data: { alias: uni.getStorageSync('alias') }
				})
			},
			
			// 检查H5微信授权
			async checkWxH5Auth() {
                // 获取alias参数
                const alias = this.getUrlParam('alias')
                if (!alias) {
                    uni.showModal({
                        title: '提示',
                        content: '无效的访问链接，请重新打开',
                        showCancel: false
                    })
                    return
                }

				const token = uni.getStorageSync(alias + '_token')
				if (!token) {
					await auth.wxH5Login()
				}
			},
			
			// 获取url参数
			getUrlParam(name) {
				const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
				const r = window.location.search.substr(1).match(reg)
				if (r != null) return decodeURIComponent(r[2])
				return null
			},
		}
	}
</script>

<style>
	/*每个页面公共css */
	page {
		background-color: #f6f7fb;
	}
</style>
